#include <REGX52.H>
#include "Timer0.h"
#include "Key.h"
#include "Nixie.h"
#include "Delay.h"
#include "AT24C02.h"

unsigned char KeyNum;

unsigned char min,sec,minisec;

unsigned char RunFlag;

void main()
{
	Timer0Init();
	while(1)
	{
		KeyNum=Key();
		if(KeyNum==1)
		{
			RunFlag=!RunFlag;
		}
		if(KeyNum==2)
		{
			min=0;
			sec=0;
			minisec=0;
		}
		if(KeyNum==3)
		{
			AT24C02_WriteByte(0,min);
			Delay(5);
			AT24C02_WriteByte(1,sec);
			Delay(5);
			AT24C02_WriteByte(2,minisec);
			Delay(5);
		}
		if(KeyNum==4)
		{
			min=AT24C02_ReadByte(0);
			sec=AT24C02_ReadByte(1);
			minisec=AT24C02_ReadByte(2);
		}
		Nixie_SetBuf(1,min/10);
		Nixie_SetBuf(2,min%10);
		Nixie_SetBuf(3,11);
		Nixie_SetBuf(4,sec/10);
		Nixie_SetBuf(5,sec%10);
		Nixie_SetBuf(6,11);
		Nixie_SetBuf(7,minisec/10);
		Nixie_SetBuf(8,minisec%10);
	}
}

void Sec_Loop(void)
{
	if(RunFlag)
	{
		minisec++;
		if(minisec>99)
		{
			minisec=0;
			sec++;
			if(sec>59)
			{
				sec=0;
				min++;
				if(min>59)
				{
					min=0;
				}
			}
		}
	}
}

void Timer0_Routine() interrupt 1
{
	static unsigned int T0Count1,T0Count2,T0Count3;
	TL0 = 0x66;
	TH0 = 0xFC;
	T0Count1++;
	if(T0Count1>=20)
	{
		T0Count1=0;
		Key_Loop();
	}
	T0Count2++;
	if(T0Count2>=2)
	{
		T0Count2=0;
		Nixie_Loop();
	}
	T0Count3++;
	if(T0Count3>=10)
	{
		T0Count3=0;
		Sec_Loop();
	}
}